package com.example.ex2.controller;

import com.example.ex2.common.CommonResponse;
import com.example.ex2.domain.User;
import com.example.ex2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService UserService;

    @PostMapping("/User")
    public CommonResponse<User> addUser(@RequestBody User User){
        System.out.println(User);
        String link = "http://localhost:8080/User";
        if(UserService.addUserByUser(User))
            return CommonResponse.createForSuccess("新增成功", link);
        else
            return CommonResponse.createForError("新增失败",link);
    }

    @DeleteMapping("/User/{id}")
    public CommonResponse<User> deleteUser(@PathVariable("id") int id){
        String link = "http://localhost:8080/User/" + Integer.toString(id);
        if(UserService.deleteUserById(id))
            return CommonResponse.createForSuccess("删除成功",link);
        else
            return CommonResponse.createForError("删除失败",link);
    }

    @GetMapping("/User")
    public CommonResponse<List<User>> getAllUsers(){
        String link = "http://localhost:8080/User";
        List<User> UserList = UserService.selectAllUsers();
        if(UserList.size() > 0)
            return CommonResponse.createForSuccess("查询成功", UserList, link);
        else
            return CommonResponse.createForError("查询不到相关数据",link);
    }

    @PutMapping("/User")
    public CommonResponse<User> updateUser(@RequestBody User User){
        String link = "http://localhost:8080/User";
        if(UserService.updateUserByUser(User))
            return CommonResponse.createForSuccess("更新成功", link);
        else
            return CommonResponse.createForError("更新失败",link);
    }

    @PutMapping("/User/{id}")
    public CommonResponse<User> updateUser(@PathVariable("id") int id){
        String link = "http://localhost:8080/User/" + Integer.toString(id);

        if(UserService.resetUserPassword(id))
            return CommonResponse.createForSuccess("重置密码成功", link);
        else
            return CommonResponse.createForError("重置密码失败",link);
    }
}
